package com.example.springbootdemo.config;


import com.example.springbootdemo.constant.BaseException;
import com.example.springbootdemo.constant.ErrCode;
import com.example.springbootdemo.constant.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.View;

import java.util.Map;
import java.util.Objects;


/**
 * * 基础异常处理器
 * *
 * * 在本处理器中 处理所有未进入controller就产生的异常，例如：
 * * * jwt过滤器 产生的异常
 * * * 无权限 产生的异常
 * *
 * * @author Gong.Yang
 */
@RestController
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasedErrorHandler implements ErrorController {
    @RequestMapping
    @ResponseStatus(HttpStatus.OK)
    public Result error(HttpServletRequest request) {
        Object attribute = request.getAttribute("javax.servlet.error.exception");
        BaseException baseException = (BaseException) attribute;
        if (Objects.isNull(baseException)) {
            baseException = ErrCode.NOTFOUND.getException();
        }

        return Result.form(baseException.getCode(), null, baseException.getMessage());
    }

    @RequestMapping(
            produces = {"text/html"}
    )
    public View errorHtml() {
        return new View() {
            @Override
            public void render(
                    Map<String, ?> model,
                    HttpServletRequest request,
                    HttpServletResponse response
            ) throws Exception {
                System.out.println(model);
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<h3>你是不是迷路啦~</h3>");
            }
        };
    }
}

